package com.qf.person.utils;

import com.qf.person.advanced.RowMapper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wangyu 增加复用 增删改查共性内容
 * @Classname: DaoUtils
 * @Description: TEST
 * @date 2022-04-07 17:02
 */
public class DaoUtils<T> {
    public int commonsUpdate(String sql, Object... args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        connection = Dbutils.getConnection();
        try {
            preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }
            int result = preparedStatement.executeUpdate();
            return result;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            Dbutils.closeAll(null, preparedStatement, null);
        }
        return 0;
    }

    public List<T> commonsSelect(String sql, RowMapper<T> rowMapper, Object... args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        List<T> list = new ArrayList<>();
        connection = Dbutils.getConnection();
        try {
            preparedStatement = connection.prepareStatement(sql);
            if (args != null) {
                for (int i = 0; i < args.length; i++) {
                    preparedStatement.setObject(i + 1, args[i]);
                }
            }
            resultSet = preparedStatement.executeQuery();

            while (resultSet.next()) {
                T t = rowMapper.getRow(resultSet);  // 调用者提供的方法完成ORM
                list.add(t);
            }
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            Dbutils.closeAll(null, preparedStatement, null);
        }
        return null;
    }
}
